﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using personalplaner.business.common;
using personalplaner.common.mvvm.binding;
using personalplaner.gui.common.viewmodels;

namespace personalplaner.gui.common.views
{
	/// <summary>
	/// Interaction logic for LoginDialog.xaml
	/// </summary>
	public partial class LoginDialog : Window
	{
		public LoginDialog(LoginData logindata)
		{
			InitializeComponent();

            Loaded += new RoutedEventHandler(LoginDialog_Loaded);

			txtPassword.Password = logindata.Password;

			var dc = DataContext as LoginDialogViewModel;
			if (dc == null)
				return;

			dc.LoginData = logindata;
            dc.MoveFocus += new EventHandler<MoveFocusEventArgs>(DataContext_MoveFocus);
		}

        void DataContext_MoveFocus(object sender, MoveFocusEventArgs e)
        {
            if (e.FocusedProperty == "LoginData.Password")
                txtPassword.Focus();
        }

        void LoginDialog_Loaded(object sender, RoutedEventArgs e)
        {
            var dc = DataContext as LoginDialogViewModel;
            if (dc == null)
                return;

            dc.Loaded();
        }

		public LoginData LoginData
		{
			get
			{
				var dc = DataContext as LoginDialogViewModel;
				if (dc != null)
					return dc.LoginData;

				return null;
			}
			set
			{
				var dc = DataContext as LoginDialogViewModel;
				if (dc != null)
					dc.LoginData = value;
			}
		}

		private void Text_LostFocus(object sender, RoutedEventArgs e)
		{
			SetPassword();
		}
		
		private void Cancel_Click(object sender, RoutedEventArgs e)
		{
			this.DialogResult = false;
			this.Close();
		}

		public void SetPassword()
		{
			var dc = DataContext as LoginDialogViewModel;
            if (dc != null && dc.LoginData != null && dc.LoginData.Password != txtPassword.Password)
            {
                dc.LoginData.Password = txtPassword.Password;
                dc.ReloadDatabases();
            }
		}

		private void Password_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
				SetPassword();
		}     
	}
}
